package com.antis.olsl.magic.analysis;

import android.text.TextUtils;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.antis.olsl.arouterlib.MagicRoutePath;
import com.antis.olsl.base.BaseActivity;
import com.antis.olsl.library.bean.MenuInfo;
import com.antis.olsl.library.dialog.ChooseDateDialog;
import com.antis.olsl.library.dialog.ChooseSalesroomsOrWarehouseDialog;
import com.antis.olsl.library.dialog.ChooseTypeDialog;
import com.antis.olsl.magic.databinding.ActivityViolenceAnalysisBinding;
import com.antis.olsl.magic.response.GetTopAnalysisDetailResp;
import com.antis.olsl.magic.response.GetTopAnalysisTotalResp;
import com.antis.olsl.library.response.SalesroomOrWarehouseInfo;
import com.antis.olsl.base.utils.ToastUtil;
import com.antis.olsl.library.widget.ChooseSalesroomOrWarehouseView;
import com.antis.olsl.magic.R;
import com.antis.olsl.magic.adapter.Top60DetailAdapter;
import com.antis.olsl.magic.adapter.Top60ItemAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.trello.rxlifecycle2.LifecycleTransformer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import timber.log.Timber;

/**
 * 暴力分析
 *
 * @author hhh
 */
@Route(path = MagicRoutePath.ACTIVITY_VIOLENCE_ANALYSIS)
public class ViolenceAnalysisActivity extends BaseActivity<ActivityViolenceAnalysisBinding> implements ViolenceAnalysisContract.View,
        ChooseSalesroomsOrWarehouseDialog.ChooseSalesroomOrWarehouseListener,
        ChooseSalesroomOrWarehouseView.ChooseSalesroomOrWarehouseListener, ChooseDateDialog.ChooseDateListener, View.OnClickListener {

//    @BindView(R2.id.tv_date)
//    TextView tvDate;
//    @BindView(R2.id.chooseSalesroomOrWarehouseView)
//    ChooseSalesroomOrWarehouseView chooseSalesroomOrWarehouseView;
//    @BindView(R2.id.text_title)
//    TextView mTextTitle;
//    @BindView(R2.id.text_detail)
//    TextView mTextDetail;
//    @BindView(R2.id.recyclerView)
//    RecyclerView mRecyclerView;
//    @BindView(R2.id.recycler_content)
//    RecyclerView mRecyclerContent;
//    @BindView(R2.id.layout_recycler)
//    LinearLayout mLayoutRecycler;

    private String mTopType;

    private ArrayList<MenuInfo> menuInfos = new ArrayList<>();
    private MenuInfo menuInfo;

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private SimpleDateFormat textDateFormat = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());

    private Date startDate;
    private Date endDate;

    private boolean chooseAllSalesroom = true;
    private ArrayList<SalesroomOrWarehouseInfo> salesroomInfos = new ArrayList<>();
    private ArrayList<SalesroomOrWarehouseInfo> selectedSalesroomInfos = new ArrayList<>();
    private ChooseSalesroomsOrWarehouseDialog mDialog;

    private ChooseDateDialog chooseDateDialog;
    private ChooseTypeDialog chooseTypeDialog;
    private ViolenceAnalysisPresenter mPresenter;

    private int pageNum = 1;
    private boolean isEnd;

    private String salesRoomIds = "";
    private String salesRoomName = "";
    private SalesroomOrWarehouseInfo mInfo;
    private Top60ItemAdapter mTop60ItemAdapter;
    private Top60DetailAdapter mAdapter;

    private List<GetTopAnalysisDetailResp.ContentBean> mList = new ArrayList<>();
    private List<GetTopAnalysisTotalResp.ContentBean> mTop60List = new ArrayList<>();

    @Override
    protected ActivityViolenceAnalysisBinding getViewBinding() {
        return ActivityViolenceAnalysisBinding.inflate(getLayoutInflater(), baseBinding.getRoot(), true);
    }

    @Override
    protected void initPresenter() {
        super.initPresenter();
        mPresenter = new ViolenceAnalysisPresenter();
        mPresenter.takeView(this);
    }

    @Override
    protected void initViews() {
        initDate();

        initMenu();

        viewBinding.layoutChooseSalesroomOrWarehouse.chooseSalesroomOrWarehouseView.setSalesroomOrWarehouseInfos(null);
        viewBinding.layoutChooseSalesroomOrWarehouse.chooseSalesroomOrWarehouseView.setChooseSalesroomOrWarehouseListener(this);

        mTop60ItemAdapter = new Top60ItemAdapter(R.layout.item_top60_item, mTop60List);
        viewBinding.recyclerContent.setLayoutManager(new LinearLayoutManager(this));
        viewBinding.recyclerContent.setAdapter(mTop60ItemAdapter);
        mTop60ItemAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.layout_title) {
                    GetTopAnalysisTotalResp.ContentBean bean = mTop60List.get(position);
                    String strSalesRoomName;
                    if (!TextUtils.isEmpty(salesRoomName)) {
                        strSalesRoomName = salesRoomName;
                    } else {
                        strSalesRoomName = "全部门店";
                    }
                    ARouter.getInstance()
                            .build(MagicRoutePath.ACTIVITY_TOP60_ITEM_DETAIL)
                            .withSerializable("bean", bean)
                            .withString("salesRoomIds", salesRoomIds)
                            .withString("salesRoomName", strSalesRoomName)
                            .withString("startDate", simpleDateFormat.format(startDate))
                            .withString("endDate", simpleDateFormat.format(endDate))
                            .navigation();
                }
            }
        });

        mAdapter = new Top60DetailAdapter(R.layout.item_table, mList);
        viewBinding.layoutTopItem.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        viewBinding.layoutTopItem.recyclerView.setAdapter(mAdapter);
//        mAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
//            @Override
//            public void onLoadMore() {
//                mRecyclerView.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (isEnd) {
//                            mAdapter.getLoadMoreModule().loadMoreEnd();
//                        } else {
//                            loadItemList(mTopType);
//                        }
//                    }
//                }, 200);
//            }
//        });

        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                GetTopAnalysisDetailResp.ContentBean bean = mList.get(position);
                ARouter.getInstance()
                        .build(MagicRoutePath.ACTIVITY_COMMODITY_DETAIL)
                        .withSerializable("bean", bean)
                        .navigation();
            }
        });

        viewBinding.textDetail.setOnClickListener(this);
        viewBinding.layoutType.setOnClickListener(this);
        viewBinding.rlChooseDate.setOnClickListener(this);
    }

    @Override
    protected void initData() throws IllegalAccessException {
        loadData();
    }

    private void loadData() {
        Map<String, Object> map = new HashMap<>(3);
        map.put("shopId", salesRoomIds);
        map.put("startTime", dateFormat.format(startDate));
        map.put("endTime", dateFormat.format(endDate));
        mPresenter.getViolenceAnalysis(map);
    }

    private void initDate() {
        Calendar calendar = Calendar.getInstance();

        endDate = new Date();
        calendar.setTime(endDate);
        //初始进来查询近7天的数据
        calendar.add(Calendar.DATE, -7);
        startDate = calendar.getTime();
        setDateText();
    }

    private void initMenu() {
        MenuInfo info = new MenuInfo();
        info.id = "1";
        info.name = "总表";
        info.choose = true;
        menuInfos.add(info);

        MenuInfo info2 = new MenuInfo();
        info2.id = "2";
        info2.name = "数量";
        info2.choose = false;
        menuInfos.add(info2);

        MenuInfo info3 = new MenuInfo();
        info3.id = "3";
        info3.name = "金额";
        info3.choose = false;
        menuInfos.add(info3);

        MenuInfo info4 = new MenuInfo();
        info4.id = "4";
        info4.name = "毛利";
        info4.choose = false;
        menuInfos.add(info4);

        MenuInfo info5 = new MenuInfo();
        info5.id = "5";
        info5.name = "数量金额重叠";
        info5.choose = false;
        menuInfos.add(info5);

        MenuInfo info6 = new MenuInfo();
        info6.id = "6";
        info6.name = "数量毛利重叠";
        info6.choose = false;
        menuInfos.add(info6);

        MenuInfo info7 = new MenuInfo();
        info7.id = "7";
        info7.name = "金额毛利重叠";
        info7.choose = false;
        menuInfos.add(info7);

        menuInfo = info;
    }

    private void setDateText() {
        String date = textDateFormat.format(startDate) + "-" + textDateFormat.format(endDate);
        viewBinding.tvDate.setText(date);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mPresenter) {
            mPresenter.unSubscribe();
        }

        if (null != chooseTypeDialog) {
            chooseTypeDialog.dismiss();
        }
    }

    @Override
    public void clickChooseListener() {
        if (salesroomInfos == null || salesroomInfos.size() == 0) {
            getWarehouseInfoList();
        } else {
            mDialog = new ChooseSalesroomsOrWarehouseDialog(this, 0, salesroomInfos, ViolenceAnalysisActivity.this);
        }
    }

    /**
     * 获取门店或仓库列表
     */
    private void getWarehouseInfoList() {
        HashMap<String, Object> map = new HashMap<>();
        mPresenter.getSalesroomInfoList(map);
    }

    @Override
    public void clickPhone(String phone) {

    }

    @Override
    public void onChooseSalesroomOrWarehouseListener(boolean isChooseAll, ArrayList<SalesroomOrWarehouseInfo> choosedFiledInfos, ArrayList<SalesroomOrWarehouseInfo> sourceInofs, int selectedIndex) {
        chooseAllSalesroom = isChooseAll;
        salesroomInfos = sourceInofs;
        selectedSalesroomInfos = choosedFiledInfos;
        pageNum = 1;
        if (selectedIndex == -1) {
            salesRoomIds = "";
            viewBinding.layoutChooseSalesroomOrWarehouse.chooseSalesroomOrWarehouseView.setSalesroomOrWarehouseInfos(null);
        } else {
            salesRoomIds = filterIds();
        }
        flushData();
    }

    public String filterIds() {
        ArrayList<SalesroomOrWarehouseInfo> infos = (chooseAllSalesroom ? salesroomInfos : selectedSalesroomInfos);
        String name = "";
        String ids = "";
        for (int i = 0; i < infos.size(); i++) {
            ids += TextUtils.isEmpty(ids) ? infos.get(i).getId() : "," + infos.get(i).getId();
            if (chooseAllSalesroom) {
                continue;
            }
            name += TextUtils.isEmpty(name) ? infos.get(i).getName() : "," + infos.get(i).getName();
        }
        boolean chooseALL = false;
        if (chooseAllSalesroom) {
            name = "全部门店";
            chooseALL = true;
        }

        if (infos.size() > 0) {
            mInfo = infos.get(0);
        }
        salesRoomName = name;
        viewBinding.layoutChooseSalesroomOrWarehouse.chooseSalesroomOrWarehouseView.setSalesroomOrWarehouseInfos(infos);
        return ids;
    }

    private void flushData() {
        if (menuInfo.id.equals("1")) {
            loadData();
        } else {
            loadItemList(menuInfo.id);
        }
    }

    private void loadItemList(String topType) {
        String temp;
        switch (topType) {
            case "2":
                temp = "1";
                break;
            case "3":
                temp = "2";
                break;
            case "4":
                temp = "3";
                break;
            default:
                temp = topType;
                break;
        }
        Map<String, Object> map = new HashMap<>(7);
        map.put("shopId", salesRoomIds);
        map.put("startTime", dateFormat.format(startDate));
        map.put("endTime", dateFormat.format(endDate));
        map.put("analysisType", temp);
//        map.put("pageNum", pageNum);
//        map.put("pageSize", 10);
        mPresenter.getItemList(map);
    }

    @Override
    public void getSalesroomInfoListSuccess(List<SalesroomOrWarehouseInfo> list) {
        salesroomInfos.clear();
        salesroomInfos.addAll(list);
        Timber.tag("hhh").e("getSalesroomInfoListSuccess resp= " + list.size());

        mDialog = new ChooseSalesroomsOrWarehouseDialog(this, 0, salesroomInfos, ViolenceAnalysisActivity.this);
    }

    @Override
    public void getSalesroomInfoListFailure(String msg) {
        Timber.tag("hhh").e("getSalesroomInfoListFailure msg= " + msg);
        if (TextUtils.isEmpty(msg)) {
            msg = "请求失败,请稍后重试";
        }
        ToastUtil.showToast(this, msg);
    }

    @Override
    public void getViolenceAnalysisSuccess(List<GetTopAnalysisTotalResp.ContentBean> list) {
        mTop60List.clear();
        mTop60List.addAll(list);
        mTop60ItemAdapter.setList(mTop60List);
    }

    @Override
    public void getViolenceAnalysisFailure(String msg) {
        Timber.tag("hhh").e("getViolenceAnalysisFailure msg= " + msg);
        if (TextUtils.isEmpty(msg)) {
            msg = "请求失败,请稍后重试";
        }
        ToastUtil.showToast(this, msg);
    }

    @Override
    public void getItemListSuccess(List<GetTopAnalysisDetailResp.ContentBean> list) {
        if (pageNum == 1) {
            mList.clear();
        }
        if (list.size() > 0) {
            mList.addAll(list);
        }
//        if (list.size() < 10) {
//            isEnd = true;
//        } else {
//            isEnd = false;
//            pageNum += 1;
//        }
        mAdapter.setList(mList);
        mAdapter.getLoadMoreModule().loadMoreComplete();
    }

    @Override
    public void getItemListFailure(String msg) {
        Timber.tag("hhh").e("getItemListFailure msg= " + msg);
        if (TextUtils.isEmpty(msg)) {
            msg = "请求失败,请稍后重试";
        }
        ToastUtil.showToast(this, msg);
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.bindToLifecycle();
    }

    private void jumpDetail() {
        String name;
        String id;
        if (null != mInfo) {
            name = mInfo.getSalesroomName();
            id = mInfo.getId();
        } else {
            name = "全部门店";
            id = "";
        }
        ARouter.getInstance()
                .build(MagicRoutePath.ACTIVITY_VIOLENCE_ANALYSIS_DETAIL_LIST)
                .withString("startDate", dateFormat.format(startDate))
                .withString("endDate", dateFormat.format(endDate))
                .withString("showStartDate", textDateFormat.format(startDate))
                .withString("showEndDate", textDateFormat.format(endDate))
                .withString("name", name)
                .withString("id", id)
                .navigation();
    }

    private void chooseType() {
        chooseTypeDialog = new ChooseTypeDialog(this, menuInfos, new ChooseTypeDialog.ChooseTypeListener() {
            @Override
            public void onChooseTypeListener(int selectedIndex) {
                MenuInfo menuInfo = menuInfos.get(selectedIndex);
                Timber.tag("hhh").e("menuInfo= " + menuInfo.name);
                viewBinding.textTitle.setText(menuInfo.name);
                mTopType = menuInfo.id;
                if (menuInfo.id.equals("1")) {
                    viewBinding.textDetail.setVisibility(View.VISIBLE);
                    viewBinding.recyclerContent.setVisibility(View.VISIBLE);
                    viewBinding.layoutTopItem.layoutRecycler.setVisibility(View.GONE);
                    loadData();
                } else {
                    viewBinding.textDetail.setVisibility(View.GONE);
                    viewBinding.recyclerContent.setVisibility(View.GONE);
                    viewBinding.layoutTopItem.layoutRecycler.setVisibility(View.VISIBLE);
                    pageNum = 1;
                    loadItemList(mTopType);
                }
            }
        });
    }

    @Override
    public void getDateListener(String tag, int year, int quarter, int month, int week, int day) {
        Date tmpDate = new Date();
        try {
            tmpDate = simpleDateFormat.parse(year + "-" + month + "-" + day);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (tmpDate.getTime() - System.currentTimeMillis() > 0) {
            ToastUtil.showToast(this, "选择时间不能超过当前时间");
            return;
        }
        if ("startDate".equals(tag)) {
            startDate = tmpDate;
            chooseDateDialog.dismiss();
            chooseDateDialog = new ChooseDateDialog(this, "选择结束时间", endDate, this, "endDate");
        } else {
            if (tmpDate.getTime() - startDate.getTime() < 0) {
                ToastUtil.showToast(this, "结束时间必须大于开始时间");
                return;
            }
            endDate = tmpDate;
            chooseDateDialog.dismiss();
            pageNum = 1;
            flushData();
        }
        setDateText();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.text_detail) {
            jumpDetail();
        } else if (id == R.id.layout_type) {
            chooseType();
        } else if (id == R.id.rl_chooseDate) {
            chooseDateDialog = new ChooseDateDialog(this, "选择时间", startDate, this, "startDate");
        }
    }
}
